package com.petshop.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.petshop.pojo.PetProduct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.petshop.utils.RedisConstant.CACHE_NULL_TTL;

@Slf4j
@Component
public class RedisCacheUtil {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisCacheUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void Set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value));
    }

    public <R, ID> R queryWithMutex(
            String keyPrefix,
            ID id,
            Class<R> clazz,
            Function<ID, R> dbFallBack,
            Long time,
            TimeUnit timeUnit) {
        String key = keyPrefix + id;
        PetProduct petProduct;
        //1.从redis查询宠物商品缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在就直接返回
            return JSONUtil.toBean(json, clazz);
        }
        //判断命中的是不是空值
        if (json != null) {
            return null;
        }
        //缓存中不存在，查询数据库
        R r = dbFallBack.apply(id);
        //5.库存中没有该商品,返回null
        if (r == null) {
            //把空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.库存存在该商品，写入redis，采用超时剔除的缓存更新策略，30分钟后删除
        this.Set(key, json, time, timeUnit);
        //8.返回
        return r;
    }


}
